import {
  login,
  logout,
  getUserInfo,
} from '@/api/user'
import { setToken, getToken } from '@/libs/utils'
export default {
  state: {
    user: '', //用户
    level: '', //权限
    avatarImgPath: '',
    token: getToken(),
    access: '',  //权限
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setuser (state, user) {
      state.user = user
    },
    setToken (state, token) {
      state.token = token;
      setToken(token)
    },
    setAccess (state, access) {
      state.access = access
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
  },
  getters: {
    getToken:state =>state.token,
    getUser:stats => stats.user
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { name, password,googlekey }) {
      name = name.trim();
      googlekey = googlekey.trim();
      return new Promise((resolve, reject) => {
        login({
          name,
          password,
          googlekey
        }).then(res => {
          const data = res.data;
          if(data.code == 1000){
            commit('setToken', data.data.token);
            resolve(data.data.token)
          }else{
            reject(data.data.msg)
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state,commit,dispatch}) {
      commit('setuser', '');
      commit('setToken', '');
      dispatch('quant_logOut', null, {root: true});  //清空quant下logOut
      dispatch('trade_logOut', null, {root: true}); //清空trade下logOut
      dispatch('other_logOut', null, {root: true})  //清空trade下logOut
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data.data;
            commit('setuser', data.user);
            commit('setAccess', data.access);
            commit('setHasGetInfo', true);
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
  },
}
